use log;

// 获取本地IP地址
pub fn get_local_ip() -> Result<String, String> {
    if let Ok(conn) = std::net::TcpStream::connect("8.8.8.8:80") {
        if let Ok(addr) = conn.local_addr() {
            let ip = addr.ip();
            if !ip.is_loopback() {
                return Ok(ip.to_string());
            }
        }
    }
    if let Ok(interfaces) = get_if_addrs::get_if_addrs() {
        for interface in interfaces {
            if !interface.is_loopback() && interface.addr.ip().is_ipv4() {
                return Ok(interface.addr.ip().to_string());
            }
        }
    }
    Ok("127.0.0.1".to_string())
}

// 获取与目标IP同网段的本地IP地址
pub fn get_local_ip_for_target(target_ip: &str) -> Result<String, String> {
    let target_ip = target_ip.parse::<std::net::IpAddr>()
        .map_err(|_| format!("无效的目标IP地址: {}", target_ip))?;
    if let Ok(interfaces) = get_if_addrs::get_if_addrs() {
        for interface in interfaces {
            if !interface.is_loopback() && interface.addr.ip().is_ipv4() {
                let local_ip = interface.addr.ip();
                if is_same_subnet(local_ip, target_ip, 24) {
                    log::info!("找到同网段IP: {} (目标: {})", local_ip, target_ip);
                    return Ok(local_ip.to_string());
                }
            }
        }
    }
    if let Ok(conn) = std::net::TcpStream::connect("8.8.8.8:80") {
        if let Ok(addr) = conn.local_addr() {
            let ip = addr.ip();
            if !ip.is_loopback() {
                log::info!("使用默认IP: {} (目标: {})", ip, target_ip);
                return Ok(ip.to_string());
            }
        }
    }
    log::warn!("使用回环地址: 127.0.0.1 (目标: {})", target_ip);
    Ok("127.0.0.1".to_string())
}

// 检查两个IP是否在同一网段
pub fn is_same_subnet(ip1: std::net::IpAddr, ip2: std::net::IpAddr, prefix_len: u8) -> bool {
    if ip1.is_ipv4() && ip2.is_ipv4() {
        let ip1_u32 = match ip1 { std::net::IpAddr::V4(ip) => u32::from(ip), _ => return false };
        let ip2_u32 = match ip2 { std::net::IpAddr::V4(ip) => u32::from(ip), _ => return false };
        let mask = if prefix_len == 0 { 0 } else { (1u32 << (32 - prefix_len)) - 1 };
        (ip1_u32 & !mask) == (ip2_u32 & !mask)
    } else { false }
}


